﻿module game.texturemanager;

import game.units;

import gamelib.graphics.renderer2d.renderer;
public import gamelib.graphics.renderer2d.texture;
public import gamelib.graphics.renderer2d.textureview;

import gamelib.types;
import gamelib.graphics.graph;
import gamelib.graphics.surface;

final class TextureManagerBase(alias TexturesList)
{
private:
    Renderer mRenderer;
    Texture[] mTextures;
    TextureView[string] mViews;

    static bool contains(in string str) pure nothrow
    {
        foreach(s;TexturesList)
        {
            if(s == str) return true;
        }
        return false;
    }
public:
    this(Renderer ren) pure nothrow
    {
        mRenderer = ren;
    }

    ~this() pure nothrow
    {
        assert(mTextures.length == 0);
        assert(mRenderer is null);
    }

    void load()
    {
        import gamelib.util: TupleRange;
        foreach(i;TupleRange!(0,TexturesList.length))
        {
            enum str = TexturesList[i];
            mixin("import texm=game.gfx."~str~";");
            auto surf = new FFSurface!(texm.LayerColorT)(texm.Width, texm.Height);
            scope(exit) surf.dispose();
            surf.fill(ColorTransparentWhite);
            foreach(j;0..texm.NumLayers)
            {
                poly(surf, texm.LayerPoints[j][0..$], texm.LayerColor[j]);
            }
            auto tex = new Texture(mRenderer, surf);
            scope(failure) tex.dispose();
            mTextures ~= tex;
            scope(failure) mTextures.length--;
            mViews[str] = new TextureView(tex);
        }
    }

    void dispose() nothrow
    {
        foreach(t;mTextures)
        {
            assert(t !is null);
            t.dispose();
        }

        mTextures.length = 0;
        mViews = mViews.init;
        mRenderer = null;
    }

    @property auto texture(string str)() pure
    {
        static assert(contains(str), "Texture \""~str~"\" not in list");
        assert(mRenderer !is null);
        auto texview = mViews.get(str, null);
        assert(texview !is null);
        return texview;
    }
}

